<?php
require_once 'twitter.php';
require_once 'config.php';

class peetweet extends Twitter 
{
	public function __construct($username = null, $password = null)
    {
        if ((string)$password !== "")
            $password = decrypt((string)$password, SECURE_KEY);
        parent::__construct($username, $password);
    }
    
    public function isUserSet() 
    {
        return ((string)$this->username !== '' && (string)$this->password !== '');
    }

    private function keyED($txt,$encrypt_key) {
		$encrypt_key = md5($encrypt_key);
		$ctr=0;
		$tmp = "";
		
		for ($i=0;$i<strlen($txt);$i++) {
			if ($ctr==strlen($encrypt_key)) $ctr=0;
			$tmp.= substr($txt,$i,1) ^ substr($encrypt_key,$ctr,1);
			$ctr++;
		}
		return $tmp;
    }

	private function encrypt($txt,$key) {
		srand((double)microtime()*1000000);
		$encrypt_key = md5(rand(0,32000));
		$ctr=0;
		$tmp = "";
		
		for ($i=0;$i<strlen($txt);$i++) {
			if ($ctr==strlen($encrypt_key)) $ctr=0;
			$tmp.= substr($encrypt_key,$ctr,1) . (substr($txt,$i,1) ^ substr($encrypt_key,$ctr,1));
			$ctr++;
		}
		
		return $this->keyED($tmp,$key);
	}

	private function decrypt($txt, $key) {

		$txt = $this->keyED($txt,$key);
		$tmp = "";

		for ($i=0;$i<strlen($txt);$i++) {
			$md5 = substr($txt,$i,1);
			$i++;
			$tmp.= (substr($txt,$i,1) ^ $md5);
		}

		return $tmp;
    }

    public function setUserCookie ()
    {
        $expire = time() + 60 * 60 * 24 *30; //a month
        setcookie("pt_usr", $this->username, $expire);
        setcookie("pt_psw", $this->encrypt($this->password, SECURE_KEY), $expire);
    }

    public function setEncryptedPassword($password)
    {
        $this->password = $this->decrypt($password, SECURE_KEY);
    }

    public function getMyUserName()
    {
        return $this->username;
    }

    public function endSession()
    {
        session_destroy();
        parent::endSession();
    }
}


